/* eslint-disable import/no-anonymous-default-export */
import { message } from 'antd'
import axios from 'axios'
import history from 'utils/history'
import { getToken, hasToken, removeToken } from 'utils/storage'
export const baseURL = 'http://geek.itheima.net/v1_0/'
const instance = axios.create({
  baseURL,
  timeout: 5000
})
instance.interceptors.request.use(config => {
  if (hasToken()) {
    config.headers.Authorization = `Bearer ${getToken()}`
  }
  return config
}, error => {
  return Promise.reject(error)
})
instance.interceptors.response.use(response => {
  return response.data
}, error => {
  if (error.response && error.response.status === 401) {
    //清除token
    removeToken()
    //提示信息
    message.warn('登录信息过期了', 1)
    //跳转到登录页，在非组件中，无法使用Redirect和history对象
    history.push('/login')
  }
  return Promise.reject(error)
})

export default (url, method, submitData) => {
  return instance({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
